package com.fanfanet.lesson13.controller;

import com.fanfanet.lesson13.entity.UserEntity;
import com.fanfanet.lesson13.jpa.UserJPA;
import com.fanfanet.lesson13.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserJPA userJPA;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/list2")
    public List<UserEntity> list2(){
        return userService.list();
    }

    @RequestMapping(value = "/list")
    public List<UserEntity> list(){
        return userJPA.findAll();
    }

    @RequestMapping(value = "/add")
    public String add(){
        UserEntity userEntity = new UserEntity();
        userEntity.setName("王宝财");
        userEntity.setAddress("西安市");
        userEntity.setAge(22);
        userJPA.save(userEntity);
        return "用户信息添加成功";
    }

    @RequestMapping(value = "/delete")
    public String delete(Long userId){
//        userJPA.deleteById(userId);
        return "用户信息删除失败";
    }

    @RequestMapping(value = "/age")
    public List<UserEntity> age(){
        return userJPA.nativeQuery(20);
    }

    @RequestMapping(value = "/deleteWhere")
    public String deleteWhere(){
        userJPA.deleteQuery("王宝财", 22);
        return "数据删除成功";
    }

    @RequestMapping(value = "cutpage")
    public List<UserEntity> cutPage(int page){
        UserEntity user = new UserEntity();
        user.setSize(2);
        user.setPage(page);
        //获取排序对象
        Sort.Direction sort_direction = Sort.Direction.ASC.toString().equalsIgnoreCase(user.getSord()) ? Sort.Direction.ASC : Sort.Direction.DESC;
        Sort sort = new Sort(sort_direction, user.getSidx());
        //创建分页对象
        PageRequest pageRequest = new PageRequest(user.getPage()-1, user.getSize(), sort);
        return userJPA.findAll(pageRequest).getContent();
    }
}
